<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Controllers\MaicheController;

class CateController extends Controller
{

    //利用中间件检测用户的登录状态.
    protected $middleware = ['App\Http\Middleware\Authenticate'=>[] ];


    public function catelist(Request $request){
        $res = DB::table('cates')->where('parent_id','-1')->paginate(10);
        return view('admin.catlist',['res'=>$res]);
    }
    public function catecar(Request $request,$carid,$carname){
        $rows = DB::table('cates')->where('parent_id',$carid)->paginate(10);
        $res = new MaicheController();
        $datas = $res->getData($carid,0,0,0,-1,0,0,0,0,0);
        $number = [];
        foreach($datas as $d){
            if(empty($number[$d->cate_id])){
                $number[$d->cate_id] = 1;
            }else{
                $number[$d->cate_id] += 1;
            }
        }
         // dd($number);
        return view('admin.catecar',['rows'=>$rows,'carid'=>$carid,'carname'=>$carname,'num'=>$number]);
    }

    public function addCate(){
        if(empty($_POST)){
            return view('admin.addcate');
        }else{
            $data['cate_name'] = $_POST['cate_name'];
            $data['parent_id'] = -1;
            return DB::table('cates')->insert($data)?redirect('/catelist'):"BUG";
        }
        
    }

     public function addCarxi(){
        if(empty($_POST)){
            $data = DB::table('cates')->where('parent_id',-1)->get();
            return view('admin.addcat',['data'=>$data]);
        }else{
            $data['cate_name'] = $_POST['cate_name'];
            $data['parent_id'] = $_POST['parent_id'];
            if( $data['parent_id'] == -1){
                return redirect('/addcar');
                exit();
            }
            return DB::table('cates')->insert($data)?redirect('/catelist'):"BUG";
        }
        
    }

    public function catedit($cate_id){
        if(empty($_POST)){
            $rows = DB::table('cates')->where('cate_id',$cate_id)->first();
            return view('admin.catedit',['rows'=>$rows]);
        }else{
            return DB::table('cates')->where('cate_id',$_POST['cate_id'])->update(['cate_name'=>$_POST['cate_name']])?redirect('catelist'):'BUG';
        }
        
    }

    public function catedel($cate_id){
        return DB::table('cates')->where('cate_id',$cate_id)->delete()?redirect('catelist'):'BUG';
    }


}
